<?php

namespace app\admin\controller;
use app\common\business\SysPost as SysPostBus;
use app\common\lib\toCamelCase;
use app\admin\validate\SysPost as SysPostValidate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysPost extends AuthBase
{
    //获取岗位列表查询条件
    public function postListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->get('pageNum', 1);
        $limit = $this->request->get('pageSize', 10);
        $postCode = $this->request->get('postCode',"");
        $postName = $this->request->get('postName',"");
        $status = $this->request->get("status","");
        if($postCode){
            $where[] = ['post_code', 'like', '%'.$postCode.'%'];
        }
        if($postName){
            $where[] = ['post_name', 'like', '%'.$postName.'%'];
        }
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["status", "=", $status];
        }
        $data = [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where
        ];
        return $data;
    }
    //岗位列表
    public function postList(){
        try {
            $searchData = $this->postListSearch();
            $postData = (new SysPostBus())->getNormalPost($searchData['where'],'*',$searchData['limit'],$searchData['page']);
            $postData = (new toCamelCase())->toCamelCaseArray($postData);
        }catch (\Exception $e){
            $postData = [];
        }
        return show(config("status.success"),"岗位列表",$postData);
    }

    //岗位添加
    public function postAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = [
            'post_name'=>$allParams['postName'],
            'post_sort'=>$allParams['postSort'],
            'post_code'=>$allParams['postCode'],
            'remark'=>$allParams['remark']??null,
            'status'=>$allParams['status'],
            'del_flag'=>'0',
        ];
        $validate = new SysPostValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        try {
            $result = (new \app\common\business\SysPost())->addPost($data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"新增成功",$result);
    }

    //岗位修改
    public function postEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        try {
            $result = (new \app\common\business\SysPost())->updateById($data['post_id'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改成功",$result);
    }

    //岗位详情
    public function postDetails(){
        $post = $this->request->param("post","","trim");
        if(empty($post)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $postData = (new SysPostBus())->getPostById($post);
            $postData = (new toCamelCase())->toCamelCaseArray($postData);
        }catch (\Exception $e){
            $postData = [];
        }
        return show(config("status.success"),"岗位详情",$postData);
    }

    //删除岗位
    public function postDel(){
        $post = $this->request->param("post","","trim");
        if(empty($post)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SysPostBus())->DelPostIds($post);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //导出岗位
    public function exportPost(){
        $searchData = $this->postListSearch();
        $postCount = (new SysPostBus())->getNormalPostCount($searchData['where']);
        $postData = (new SysPostBus())->getNormalPost($searchData['where'],'*',$postCount,$searchData['page']);

        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:E1'); // 假设表头只有5列
        $sheet->setCellValue('A1', '岗位数据');
        // 设置表头
        $header = ['岗位序号', '岗位编码', '岗位名称', '岗位排序', '状态'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        $sheet->getColumnDimension("A")->setWidth(15);
        $sheet->getColumnDimension("B")->setWidth(15);
        $sheet->getColumnDimension("C")->setWidth(15);
        $sheet->getColumnDimension("D")->setWidth(15);
        $sheet->getColumnDimension("E")->setWidth(15);
        // 填充数据
        $row = 3;
        foreach ($postData['data'] as $post) {
            $post['status'] = $post['status'] === '0' ? "正常" : "停用";
            $sheet->setCellValue('A' . $row, $post['post_id']);
            $sheet->setCellValue('B' . $row, $post['post_code']);
            $sheet->setCellValue('C' . $row, $post['post_name']);
            $sheet->setCellValue('D' . $row, $post['post_sort']);
            $sheet->setCellValue('E' . $row, $post['status']);
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:E2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:E2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':E' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':E' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="post.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }
}
